using System;
using Me.Prettyprint.Hector.Api;
using Me.Prettyprint.Hector.Api.Beans;
using Me.Prettyprint.Hector.Api.Factory;
using Me.Prettyprint.Hector.Api.Mutation;
using Me.Prettyprint.Hector.Api.Query;

namespace Me.Prettyprint.Cassandra.Service
{
    public class ClearCounterRow<K,N,V>
	{
        public const int DEFAULT_COUNT = 100;
        public const int DEFAULT_MUTATION_INTERVAL = 100;

        public ClearCounterRow(Keyspace keyspace, Serializer<K> keySerializer, Serializer<N> nameSerializer)
        {
            Keyspace = keyspace;
            KeySerializer = keySerializer;
            NameSerializer = nameSerializer;
            Count = DEFAULT_COUNT;
            MutateInterval = DEFAULT_MUTATION_INTERVAL;
        }
        private Keyspace Keyspace
        {
            get;
            set;
        }
        private Serializer<K> KeySerializer
        {
            get;
            set;
        }
        private Serializer<N> NameSerializer
        {
            get;
            set;
        }
        public K RowKey
        {
            get;
            set;
        }
        public string ColumnFamily
        {
            get;
            set;
        }
        public int MutateInterval
        {
            get;
            set;
        }
        public int Count
        {
            get;
            set;
        }
        public void Clear()
        {
            Mutator<K> mutator = HFactory.CreateMutator<K,N,V>(Keyspace, KeySerializer, new BatchSizeHint(1, MutateInterval));

            SliceCounterQuery<K, N> query = HFactory.CreateCounterSliceQuery(Keyspace, KeySerializer, NameSerializer).
                            SetColumnFamily(ColumnFamily).
                            SetKey(RowKey);

            SliceCounterEnumerator<K, N, V> iterator =
                            new SliceCounterEnumerator<K, N, V>(query, default(N), default(N), false, Count);

            while (iterator.HasNext())
            {
                HCounterColumn<N> column = iterator.Next();
                mutator.IncrementCounter(RowKey, ColumnFamily, column.GetName(), column.GetValue() * -1);
            }
            mutator.Execute();
        }
	}
}